﻿#include "QGraphicsViews.h"
#include <QScrollBar>
#include <QDebug>
#include "ControlItem.h"
#include "BaseItem.h"
#include <QFileDialog>
#include <QAction>
#include <QLabel>
//#include "Light.h"
//#include "IconButton.h"
#include "QGraphicsScenes.h"
#include <QHBoxLayout>
#include "ImageItem.h"



QGraphicsViews::QGraphicsViews(QWidget *parent) : QGraphicsView(parent)
{
    this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);//解决拖动是背景图片残影
    setDragMode(QGraphicsView::ScrollHandDrag);
    drawBg();
    // 隐藏水平/竖直滚动条
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setBackgroundBrush(Qt::gray);

    // 设置场景范围
    setSceneRect(INT_MIN / 2, INT_MIN / 2, INT_MAX, INT_MAX);
    //setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));

    // 反锯齿
    setRenderHints(QPainter::Antialiasing);
    item=new ImageItem;
    scene=new QGraphicsScenes;
    scene->addItem(item);
    this->setScene(scene);


    drawItem=new DrawItem;
    AddItems(drawItem);


    addAction(new QAction(QString::fromLocal8Bit("保存原图"),this));
    addAction(new QAction(QString::fromLocal8Bit("保存截图"),this));
    setContextMenuPolicy(Qt::ActionsContextMenu);

    GrayValue=new QLabel(this);//显示灰度值
    GrayValue->setStyleSheet("color:rgb(50,255,0); background-color:rgb(80,80,80,180); font-size: 23px;font-weight: 400px;");
    GrayValue->setVisible(false);
    GrayValue->setFixedWidth(160);
    //上方操作 显示区域
    fWidget=new QWidget(this);
    fWidget->setFixedHeight(60);
    auto fLayout=new QHBoxLayout(fWidget);
    fLayout->setSpacing(12);
    fLayout->setMargin(0);

    auto tmpLabel=new QLabel;
    fLayout->addWidget(GrayValue);
    fLayout->addStretch();
    //信息背景色
    tmpLabel->setStyleSheet("color:rgb(0,255,0); background-color:rgb(80,80,80); font-size: 23px;font-weight: 400px;");
    tmpLabel->setText("GrabNum :");
    //OK标志
    OKLab=new QLabel(this);
    QFont fontOk("Microsoft YaHei", 30, 75);
    OKLab->setFont(fontOk);
    OKLab->setStyleSheet("color:rgb(0,255,0);");
    OKLab->move(0,100);
    OKLab->setText("OK");
    OKLab->setVisible(false);
    //NG 标志
    NGLab=new QLabel(this);
    QFont fontNG("Microsoft YaHei", 30, 75);
    NGLab->setFont(fontNG);
    NGLab->setStyleSheet("color:rgb(255,0,0);");
    NGLab->move(0,40);
    NGLab->setText("NG");
    NGLab->setVisible(false);

    connect(item,&ImageItem::RGBValue,this,[&](QString InfoVal){

        GrayValue->setText(InfoVal);
    });

    SetType(false, false);
}

void QGraphicsViews::DispImage(QImage &Image)
{
    ImageCatch=Image.copy();
    image=QPixmap::fromImage(Image);
    item->setPixmap(image);
    GetFit();
}

void QGraphicsViews::DispPoint(QVector<QPointF> &list, QColor color)
{
    drawItem->ClearAll();
    drawItem->AddRegion(list);
}

void QGraphicsViews::AddItems(BaseItem *item)
{
    item->scale=&ZoomValue;
    this->scene->addItem(item);
}
//信息模块设定内容
void QGraphicsViews::DispInfo(int statue,int Result, QString str,bool All)
{
    if(All)
    {
        ((QLabel*)StatueInfo)->setText(str);
        switch (Result)
        {
            case -1:
            NGLab->setVisible(true);
            OKLab->setVisible(false);
                break;
            case 0:
            NGLab->setVisible(false);
            OKLab->setVisible(false);
                break;
            case 1:
            NGLab->setVisible(false);
            OKLab->setVisible(true);
                break;
            default:
                break;
        }

    }else
    {
//        ((LightButton*)StatueLight)->SetStatue(statue);
    }
}
//设定信息模块是否显示
void QGraphicsViews::SetType(bool InfoFlg, bool GrayValueFlg)
{
    item->setAcceptHoverEvents(!InfoFlg);
    GrayValue->setVisible(!InfoFlg);
    //fWidget->setVisible(InfoFlg);
}


void QGraphicsViews::SetToFit()
{
    ZoomFrame(ZoomFit);
    QScrollBar *pHbar =  this->horizontalScrollBar();
    pHbar->setSliderPosition(PixX);
    QScrollBar *pVbar = this->verticalScrollBar();
    pVbar->setSliderPosition(PixY);
}

void QGraphicsViews::ClearObj()
{
    foreach(auto item,scene->items())
    {
        if(item->type()==10)
        {
            scene->removeItem(item);
        }
    }
}
void QGraphicsViews::ZoomFrame(double value)
{
    double tmp=value/ZoomValue;
    //绝对缩放
    ZoomValue*=tmp;
    //相对上一次缩放
    this->scale(tmp,tmp);
}
void QGraphicsViews::GetFit()
{    
    if(this->width()<1||image.width()<1)
    {
        return;
    }
    //图片自适应方法
    double winWidth=this->width();
    double winHeight=this->height();
    double ScaleWidth=(image.width()+1)/winWidth;
    double ScaleHeight=(image.height()+1)/winHeight;
    double row1,column1;
    double s=0;
    if(ScaleWidth>=ScaleHeight)
    {

        row1= -(1) * ((winHeight * ScaleWidth) - image.height()) / 2;
        column1 = 0  ;
        s=1/ScaleWidth;
    }
    else
    {
        row1= 0;
        column1 = -(1.0) * ((winWidth * ScaleHeight) - image.width()) / 2 ;
        s=1/ScaleHeight;
    }

    if(ZoomFit!=s||PixX!=column1*s)
    {
        ZoomFit=s;
        PixX=column1*s;
        PixY=row1*s;
        SetToFit();
    }
}

void QGraphicsViews::drawBg()
{
    bgPix.fill(color1);
    QPainter painter(&bgPix);
    painter.fillRect(0, 0, 32, 32, color2);
    painter.fillRect(32, 32, 32, 32, color2);
    painter.end();
    //this->update();
}

void QGraphicsViews::mousePressEvent(QMouseEvent *event)
{
    QGraphicsView::mousePressEvent(event);
}
void QGraphicsViews::resizeEvent(QResizeEvent *event)
{
    GetFit();
    QGraphicsView::resizeEvent(event);
}
void QGraphicsViews::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);
}
void QGraphicsViews::mouseDoubleClickEvent(QMouseEvent *event)
{
    SetToFit();
    QGraphicsView::mouseDoubleClickEvent(event);
}
void QGraphicsViews::wheelEvent(QWheelEvent *event)
{

    if((event->delta() > 0)&&(ZoomValue >= 50))//最大放大到原始图像的50倍
    {
        return;
    }
    else if((event->delta() < 0)&&(ZoomValue <= 0.01))//图像缩小到自适应大小之后就不继续缩小
    {
        return;
    }
    else
    {
        double tmp=ZoomValue;
        if(event->delta() > 0)//鼠标滚轮向前滚动
        {
            tmp*=1.1;//每次放大10%
        }
        else
        {
            tmp*=0.9;//每次缩小10%
        }
        ZoomFrame(tmp);

        qreal x=event->pos().x()-this->width()/2;
        qreal y=event->pos().y()-this->height()/2;
        //缩放时 鼠标位置跟随
        if(event->delta() > 0)
        {
            QScrollBar *pHbar =  this->horizontalScrollBar();
            pHbar->setSliderPosition(pHbar->sliderPosition()+x*0.1);
            QScrollBar *pVbar = this->verticalScrollBar();
            pVbar->setSliderPosition(pVbar->sliderPosition()+y*0.1);
        }
        else
        {
            QScrollBar *pHbar =  this->horizontalScrollBar();
            pHbar->setSliderPosition(pHbar->sliderPosition()-x*0.1);
            QScrollBar *pVbar = this->verticalScrollBar();
            pVbar->setSliderPosition(pVbar->sliderPosition()-y*0.1);
        }

    }

}

void QGraphicsViews::drawBackground(QPainter *painter, const QRectF &rect)
{
    Q_UNUSED(rect);
    painter->drawTiledPixmap(rect, bgPix);//绘制背景曾
}

void QGraphicsViews::updateSceneRect()
{

    QRectF rectTmp = scene->sceneRect();	//获得当前view scene的区域
    QPointF ptTopLeft = rectTmp.topLeft();	//获得区域左上点和右下点坐标
    QPointF ptBottomRight = rectTmp.bottomRight();
    QPointF ptW_H = 0.5 * QPointF(rect().width(), rect().height());	//这一步主要是为了后边放大区域的范围，0.5这个系数可以修改
    ptTopLeft -= ptW_H;	//左上点向左上方平移
    ptBottomRight += ptW_H;	//右下点向右下平移
    rectTmp.setTopLeft(ptTopLeft);	//按照左上左下点修改rect的大小
    rectTmp.setBottomRight(ptBottomRight);
    scene->setSceneRect(rectTmp);//更新scene rect的范围
    qDebug()<<rectTmp;
}




